package com.block.merchant.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.service.LogFactory;
import com.block.datapush.model.result.FilterHandlerResult;
import com.block.datapush.service.IDataFilterHandleService;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantTaskInfo;
import com.block.db.mapper.MerchantTaskInfoMapper;
import com.block.merchant.service.IMerchantTaskInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.auth.AUTH;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商户推送任务表 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-08-12
 */
@Service
public class MerchantTaskInfoServiceImpl extends ServiceImpl<MerchantTaskInfoMapper, MerchantTaskInfo> implements IMerchantTaskInfoService {

    private static final Logger log = LogFactory.getMerchantLog();

    @Autowired
    IDataFilterHandleService dataFilterHandleService;
    @Autowired
    NotifyExceptionService notifyExceptionService;
    /**
     * 根据机构ID 获取可推送的机构任务
     * 需要判断机构账户余额
     *
     */
    @Override
    public List<MerchantTaskInfo> getMerchantCanPushTaskList(String infoId, MemberSourceInfo memberSourceInfo){

        List<MerchantTaskInfo> taskInfoList = this.baseMapper.getMerchantEnableTaskList(infoId);
        if (ObjectUtil.isEmpty(taskInfoList)){
            return taskInfoList;
        }

        List<MerchantTaskInfo> resultList = new ArrayList<>();
        for (MerchantTaskInfo merchantTaskInfo : taskInfoList) {
            try {
                FilterHandlerResult filterResult = dataFilterHandleService.execMerchantFilter(merchantTaskInfo, memberSourceInfo);
                // 过滤成功，且拿到价格最高的推送任务（同一个商户）
                if (filterResult.isSuccess()){
                    resultList.add(merchantTaskInfo);
                }
            }catch (Exception exception){
                exception.printStackTrace();
                String message = StrUtil.format("【taskId】:{};【infoId】:{};",
                        merchantTaskInfo.getId(), merchantTaskInfo.getInfoId());
                notifyExceptionService.notifyNoticeInfo("MERCHANT_PUSH_MANUAL", "商户任务过滤异常", message, exception);
            }
        }
        return resultList;
    }
}
